package com.lj.auth.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.lj.auth.properties.AuthApiProperties;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author luojing
 * @date 2024/8/9
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Resource
    private AuthApiProperties apiProperties;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器
        registry.addInterceptor(getSaInterceptor())
                .addPathPatterns(apiProperties.getIncludePatterns())
                .excludePathPatterns(apiProperties.getExcludePatterns());
    }

    @Bean
    @ConditionalOnMissingBean
    public SaInterceptor getSaInterceptor() {
        return new SaInterceptor(
                handler -> {
                    // OPTIONS预检请求，不做处理
                    SaRouter.match(SaHttpMethod.OPTIONS).back();
                    // 所有请求都进行校验登录
                    StpUtil.checkLogin();
                })
                // 打开注解式鉴权功能
                .isAnnotation(true);
    }

}
